package com.xuyuan.concurrent.test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockBuyTicket extends Thread {
    public static int tickets = 20;
    // static ReentrantLock reentrantLock=new ReentrantLock();
    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static byte[] bytes = new byte[0];

    public static void main(String[] args) {

        LockBuyTicket buyTicket = new LockBuyTicket();
        for (int i = 1; i < 4; i++) {
            Thread t = new Thread(buyTicket, i + "窗口-");
            t.start();
        }
        long newTime = System.currentTimeMillis();
    }

    @Override
    public void run() {

        while (sale()) ;
    }

    public boolean sale() {
        // reentrantLock.lock();
        Lock lock = readWriteLock.writeLock();
        lock.lock();
        if (tickets > 0) {
            tickets--;
            System.out.println(Thread.currentThread().getName() + "成功出票，剩余票数为" + tickets);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // reentrantLock.unlock();
            lock.unlock();
            return true;
        } else {
            System.out.println(Thread.currentThread().getName() + "余票不足，停止售票！");
            // reentrantLock.unlock();
            lock.unlock();
            return false;
        }
    }

}